package me.zhengjie.modules.power.rest;

import io.swagger.annotations.Api;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.modules.power.domain.vo.StandardResponse;
import me.zhengjie.modules.power.service.SysUserService;
import me.zhengjie.modules.power.service.dto.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * SysUserController
 *
 * @author weiruitao
 * @date 2021/11/17
 */
@CrossOrigin
@RestController
@Api(tags = "注册")
@RequestMapping("/register")
public class SysUserController {
    @Autowired
    SysUserService service;

    @Autowired
    PasswordEncoder passwordEncoder;

    @AnonymousAccess
    @PostMapping
    public StandardResponse<Object> reg(@RequestBody SysUser sysUser) {
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));

        //激活权限
        sysUser.setEnabled("1");
        //设置部门等防报错
        sysUser.setDeptId("2");
        int register = service.register(sysUser);
        int userId = service.getUserId(sysUser.getUsername());
        int addJobs = service.addJobs(userId);
        int addRoles = service.addRoles(userId);
        return register == 1 && addJobs == 1 && addRoles == 1 ?
                new StandardResponse<>(HttpStatus.CREATED.value(), 1, "注册成功", null) :
                new StandardResponse<>(HttpStatus.CREATED.value(), 0, "注册失败", null);
    }

    @GetMapping
    @AnonymousAccess
    public StandardResponse<Object> existName(String username) {
        int code = service.existName(username);
        return code == 1 ?
                new StandardResponse<>(HttpStatus.CREATED.value(), code,"用户名不存在",null):
                new StandardResponse<>(HttpStatus.CREATED.value(), code,"用户名已存在",null);
    }
}
